<?php

use Illuminate\Database\Capsule\Manager as DB;

#后台基类
abstract class ACommonController extends CommonController
{
    public function init()
    {
        parent::init();
        $this->checkAuth();
        Yaf_Dispatcher::getInstance()->autoRender();
        $this->_view->assign('uniqid', uniqid('mix'));
    }

    /**
     * @name 默认首页@基类
     */
    public function indexAction(){
        $this->_view->display( strtolower($this->controller) . '/index.html');
    }

    #验证权限
    private function checkAuth()
    {
        $this->auth = new Auth(_RBACCookieKey_);
        if (!$this->auth->isLogin()) {
            throw new \Exception('未登陆.', 402);
        }
        $this->checkRole();
    }

    private function checkRole()
    {
        #判断控制器&方法权限
        $allAuth = remember('auths_' . $this->auth->user_id, 3600, function () {
            $ownAuth = explode(',', DB::table('admin_roles')->where('id', $this->auth->roles_id)->value('menu_ids'));
            $rows    = DB::table('admin_menus')->whereIn('id', array_values($ownAuth))->where('actions', '<>', '')->whereNotNull('actions')->select('module', 'controller', 'actions')->get();
            $auth    = [];
            if ($rows->isNotEmpty()) {
                foreach ($rows as $k => $v) {
                    $allact = explode(',', $v->actions);
                    foreach ($allact as $action) {
                        array_push($auth, strtolower('/' . $v->module . '/' . $v->controller . '/' . $action));
                    }
                }
            }
            return $auth;
        });
        if (!in_array(strtolower('/' . $this->module . '/' . $this->controller . '/' . $this->action), $allAuth)) {
            throw new Exception('无访问权限.', 400);
        }
    }

}
